<?php
/**
* Upload entry point.
*@author Willy Gardiol
*@version 1.0
*@package EntryPoints
*@todo Add support for error reporting: output code here and use some JS to trigger something to show it on the client side.
*/
/**
* Specify the proper header and charset.
*/
header("Content-type: text/html; charset=utf-8");

$error_reporting_style = "html";
require_once "Engine/engine.php";

# Ensure we are logged, or die.
if ( !CoreAuth::Authorize() )
	throw new Exception("Must be logged");

# Ensure that the upload fodler exists, or create it.
$upload_dir = "site_data/temp_upload";
if (  !file_exists($upload_dir) )
	if ( !mkdir( $upload_dir ) )
		throw new Exception("Unable to create upload folder");

# Ensure we have a valid upload_name to work with.
if ( ($upload_name = Core::POSTVar("upload_name", false, "string")) === false )
	throw new Exception("Upload name is missing!");

/*
array(5) { 
["upf_0"]=>  array(5) { ["name"]=>  string(13) "auto-proxy.sh" 
						["type"]=>  string(16) "application/x-sh" 
						["tmp_name"]=>  string(14) "/tmp/phpYUUXII" 
						["error"]=>  int(0) 
						["size"]=>  int(120) } 
["upf_1"]=>  array(5) { ["name"]=>  string(14) "bookmarks.html" 
						["type"]=>  string(9) "text/html" 
						["tmp_name"]=>  string(14) "/tmp/phppq89Up" 
						["error"]=>  int(0) 
						["size"]=>  int(28240) } 
*/

$status = "No files uploaded.";
# Process each uploaded file now
if ( isset( $_FILES ) && ( count( $_FILES ) > 0 ) )
{	# Setup data storage array
	$store =  array( "name" => $upload_name,
					"session" => session_id(),
					"files" => array(),
					"filename" => "$upload_dir/$upload_name");

	# Iterate each file
	foreach ( $_FILES as $key => $item )
	{	# Ignore files that have not been uploaded properly
		if ($item["error"] == UPLOAD_ERR_OK) 
		{
			$tmp_name = $item["tmp_name"];
			$temporary = CoreUtils::TempFile();
			# Move uploaded file to temporary location
			move_uploaded_file($tmp_name, $temporary);
			# Read the file into the memory storage
			$store["files"][$key] = array(	"name" => $item["name"],
											"type" => $item["type"],
											"data" => file_get_contents( $temporary ) );
			# remove temporary file
			unlink( $temporary );
		}
	}
	# Save all files data.
	if ( count( $store["files"] ) > 0 )
	{
		file_put_contents( $store["filename"], serialize($store) );
		$status = "Uplaoded ".count( $store["files"] )." files.";
	}
}
# Barf out some HTML to satisfy the iframe
echo "<html><body style='margin:0px;padding:0px'>";
echo $status;
echo "</body></html>";
?>